<template>
	<div class="cus">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px" @close="clean">
			<el-form ref="itemDialogFormRef" :rules="rules" :model="state.ruleForm" size="default" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="节点类型" prop="nodeType">
							<el-select v-model="state.ruleForm.nodeType" class="filter-item" placeholder="请选择" @change="onNodeTypeSelect">
								<el-option v-for="item in nodeTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="节点名" prop="name">
							<el-input v-model="state.ruleForm.name"></el-input>
						</el-form-item>
					</el-col>
					<template v-if="state.ruleForm.nodeType == 'leaf'">
						<el-divider :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" content-position="center">项目信息 </el-divider>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="应用名" prop="appName">
								<el-input v-model="state.ruleForm.appName"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="应用类型" prop="appType">
								<el-select v-model="state.ruleForm.appType" class="filter-item" placeholder="请选择">
									<el-option v-for="item in appTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="所属环境" prop="env">
								<el-select v-model="state.ruleForm.env" class="filter-item" placeholder="请选择" @change="onEnvSelect">
									<el-option v-for="item in state.envOptions" :key="item.value" :label="item.label" :value="String(item.value)" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-divider :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" content-position="center">部署信息 </el-divider>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="部署类型" prop="deployType">
								<el-select v-model="state.ruleForm.deployType" class="filter-item" placeholder="请选择" @change="onDeployTypeSelectChange">
									<el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
								</el-select>
							</el-form-item>
						</el-col>
						<template v-if="state.ruleForm.deployType == 'k8s'">
							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="部署集群" prop="deployCluster">
									<el-select v-model="state.ruleForm.deployCluster" class="filter-item" placeholder="请选择" @change="onDeployClusterSelect">
										<el-option v-for="item in state.k8sClusterOptions" :key="item.value" :label="item.label" :value="String(item.value)" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="部署空间" prop="namespace">
									<el-input v-model="state.ruleForm.namespace"></el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="访问域名" prop="domain">
									<el-input v-model="state.ruleForm.domain"></el-input>
								</el-form-item>
							</el-col>
						</template>
						<template v-else-if="state.ruleForm.deployType == 'node'">
							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="主机IP" prop="deployIps">
									<el-input v-model="state.ruleForm.deployIps"></el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="部署目录" prop="deployDest">
									<el-input v-model="state.ruleForm.deployDest"></el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
								<el-form-item label="部署命令" prop="remoteCommand">
									<el-input v-model="state.ruleForm.remoteCommand"></el-input>
								</el-form-item>
							</el-col>
						</template>
					</template>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="itemDialog">
import { reactive, onMounted, ref } from 'vue';

import { ElMessage } from 'element-plus';
import { itemApi } from '/@/api/item';
import { resourceApi } from '/@/api/resource';
import Constants from '/@/constant/constants';
import lodash from 'lodash';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const itemDialogFormRef = ref();

const appTypeOptions = [
	{ value: 'java', label: 'java' },
	{ value: 'nginx', label: '前端' },
];

// const envOptions = [
// 	{ value: 'dev', label: 'dev' },
// 	{ value: 'qa', label: 'qa' },
// 	{ value: 'prod', label: 'prod' },
// ];

// const k8sClusterOptions = [
// 	{ value: 'xjt_qa', label: 'xjt_qa' },
// 	{ value: 'xjt_prod', label: 'xjt_prod' },
// 	{ value: 'iot-prod', label: 'iot-prod' },
// ];

const typeOptions = [
	{ value: 'k8s', label: 'k8s集群' },
	{ value: 'node', label: '主机' },
];

const nodeTypeOptions = [
	{ value: 'folder', label: '目录' },
	{ value: 'leaf', label: '子节点' },
];

const rules = reactive({
	name: [{ required: true, message: '名称必填', trigger: 'blur' }],
	nodeType: [{ required: true, message: '节点类型必填', trigger: 'blur' }],
	appName: [{ required: true, message: '应用名称必填', trigger: 'blur' }],
	appType: [{ required: true, message: '应用类型必填', trigger: 'blur' }],
	env: [{ required: true, message: '所属环境必填', trigger: 'blur' }],
	deployType: [{ required: true, message: '部署类型必选', trigger: 'blur' }],
	deployCluster: [{ required: true, message: '部署集群必选', trigger: 'blur' }],
	namespace: [{ required: true, message: '命名空间必填', trigger: 'blur' }],
	deployDest: [{ required: true, message: '部署目录必填', trigger: 'blur' }],
	deployIps: [{ required: true, message: '部署IP必填', trigger: 'blur' }],
	domain: [{ required: true, message: '访问域名必填', trigger: 'blur' }],
	remoteCommand: [{ required: true, message: '部署命令必填', trigger: 'blur' }],
});

const state = reactive({
	ruleForm: {
		id: undefined, // 菜单ID
		parentId: undefined, // 上级菜单
		parentPath: '',
		name: '', // 名称
		nodeType: 'folder', // 项目类型
		appName: '', // 应用名称
		appType: '', // 应用类型
		gitUrl: '',
		gitlabId: undefined,
		env: '',
		service: '',
		toolVersion: [],
		compileCommand: '',
		archive: '',
		execDir: '',
		deployCluster: '',
		cusDockerfile: '',
		deployIps: '',
		deployDest: '',
		domain: '',
		namespace: '',
		remoteCommand: '',
		deployType: undefined,
		meta: {
			parentIds: [],
		},
	},
	k8sClusterOptions: [],
	serverOptions: [],
	envOptions: [],
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
		operatorNode: undefined,
		operatorNodeData: undefined,
	},
});

// 打开弹窗
const openDialog = async (type: string, node?: any, row?: any) => {
	if (type === 'edit') {
		state.ruleForm = row;
		state.dialog.title = '修改菜单';
		state.dialog.submitTxt = '修 改';
		if (row.nodeType === 'leaf') {
			onNodeTypeSelect(state.ruleForm.nodeType);
			onDeployTypeSelectChange(state.ruleForm.deployType);
		}
	} else if (type === 'copy') {
		row.id = undefined;
		state.ruleForm = row;
		state.dialog.title = '复制项目';
		state.dialog.submitTxt = '复 制';
		if (row.nodeType === 'leaf') {
			onNodeTypeSelect(state.ruleForm.nodeType);
			onDeployTypeSelectChange(state.ruleForm.deployType);
		}
	} else {
		state.dialog.title = '新增菜单';
		state.dialog.submitTxt = '新 增';
		state.ruleForm.parentId = row.id;
		if (row.meta && row.meta.parentIds) {
			// 当前项目的所有父级ID为上级项目parentIds + 当前项目ID
			state.ruleForm.meta.parentIds = [...row.meta.parentIds, row.id];
		} else {
			state.ruleForm.meta.parentIds = [row.id];
		}
	}
	state.dialog.isShowDialog = true;
	state.dialog.type = type;
	state.dialog.operatorNode = node;
	state.dialog.operatorNodeData = row;
};

// 清空表单
const clean = () => {
	state.ruleForm = {
		id: undefined, // 菜单ID
		parentId: undefined, // 上级菜单
		parentPath: '',
		name: '', // 名称
		nodeType: 'folder', // 项目类型
		appName: '', // 应用名称
		appType: '', // 应用类型
		gitUrl: '',
		gitlabId: undefined,
		env: '',
		service: '',
		toolVersion: [],
		compileCommand: '',
		archive: '',
		execDir: '',
		deployCluster: '',
		cusDockerfile: '',
		deployIps: '',
		deployDest: '',
		domain: '',
		namespace: '',
		remoteCommand: '',
		deployType: undefined,
		meta: {
			parentIds: [],
		},
	};
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

// 节点类型改变事件
const onNodeTypeSelect = (val) => {
	if (val === 'leaf') {
		resourceApi()
			.getOptions({ types: [Constants.RESOURCE_TYPE.ENV] })
			.then((res) => {
				state.envOptions = res.data[Constants.RESOURCE_TYPE.ENV];
			})
			.catch((err) => {
				ElMessage.error(err.msg);
			});
	}
};

// 环境选择事件
const onEnvSelect = (val) => {
	state.envOptions.find((option) => {
		if (option.value === val) {
			state.ruleForm.meta.envName = option.label;
		}
	});
};

// 部署集群选择事件
const onDeployClusterSelect = (val) => {
	state.k8sClusterOptions.find((option) => {
		if (option.value === val) {
			state.ruleForm.meta.deployClusterName = option.label;
		}
	});
};

// 部署类型改变事件
const onDeployTypeSelectChange = (val) => {
	if (!val) {
		return;
	}
	let type = 0;
	if (val === 'k8s') {
		type = Constants.RESOURCE_TYPE.K8S_CLUSTER;
	} else if (val === 'node') {
		type = Constants.RESOURCE_TYPE.SERVER;
	}
	resourceApi()
		.getOptions({ types: [type] })
		.then((res) => {
			if (val === 'k8s') {
				state.k8sClusterOptions = res.data[type];
			} else if (val === 'node') {
				state.serverOptions = res.data[type];
			}
		})
		.catch((err) => {
			ElMessage.error(err.msg);
		});
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
	itemDialogFormRef.value.validate((valid: boolean) => {
		if (valid) {
			let data = lodash.cloneDeepWith(state.ruleForm, (value, key, obj) => {
				if (key === 'children' && obj === state.ruleForm) {
					return obj.nodeType == 'leaf' ? null : [];
				}
			});
			itemApi()
				.addOrUpdateItemNode(data)
				.then((res) => {
					ElMessage.success('保存成功');
					closeDialog(); // 关闭弹窗
					emit('refresh', state.dialog.type, state.dialog.operatorNode, res.data);
				})
				.catch((err) => {
					ElMessage.error(err.msg);
				});
		}
	});
};

// 页面加载时
onMounted(() => {});

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss" scoped>
.cus:deep(.el-overlay .el-overlay-dialog) {
	align-items: normal;

	.el-dialog {
		margin: 15vh auto !important;
	}
}
</style>
